package com.file.other;

import com.common.TaskPoolConfig;
import com.util.HTTPRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @author: cxt
 * @time: 2022/6/16
 * 发送请求批量下载图片
 */
@Slf4j
public class GetImage {
    private static final ThreadPoolTaskExecutor executor;

    static {
        TaskPoolConfig taskPoolConfig = new TaskPoolConfig();
        executor = taskPoolConfig.myAsyncExecutor();
    }

    /**
     * 根据url下载图片
     *
     * @param savePath 保存地址
     * @param name     保存时文件名称
     * @param url      图片地址
     * @param format   保存格式
     */
    public static void downloadImg(String savePath, String name, String url, String format) {
        // 异步执行下载逻辑
        CompletableFuture.runAsync(() -> {
            log.info("发送请求：{}", url);
            byte[] bytes = HTTPRequestUtil.SendGet(url);
            if (Objects.isNull(bytes)) {
                log.error("请求异常，请检查请求地址");
                return;
            }
            try {
                File file = new File(savePath + name + format);
                if (file.createNewFile()) {
                    log.info("文件创建成功：{}", file.getName());
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file.getPath()));
                    out.write(bytes);
                    out.flush();
                    out.close();
                } else {
                    log.error("创建文件异常:{};url:{}", name, url);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, executor);
    }

    /**
     * 解析html文件，得到url再下载
     *
     * @param htmlPath 解析文件路劲
     * @param savePath 保存图片路径
     */
    public static void byFilePath(String htmlPath, String savePath) {
        try {
            // connect可以发送一个请求，在请求设置需要的参数并获取HTML，这里直接解析
            Document document = Jsoup.parse(new File(htmlPath), "utf-8");
            // 通过元素id值来获取对应的节点
            //  Element element = document.getElementById(String  id);
            // 通过标签名来获取
            //  Elements elements = document.getElementsByTag(String tagName);
            // 通过类名来获取
            //  Elements elements = document.getElementsByClass(String className);
            // 通过属性名来获取
            //  Elements elements = document.getElementsByAttribute(String key);
            // 通过指定属性名称和属性值来获取节点对象
            //  Elements elements = document.getElementsByAttributeValue(String key, String value);
            // 获取所有节点元素
            //  Elements elements = document.getAllElements();

            Elements span = document.getElementsByTag("span");

            for (Element element : span) {
                String title = element.attr("title");
                if (StringUtils.isNotEmpty(title)) {
                    String regex = "(^\\[*)|(]$)";
                    String name = title.replaceAll(regex, ""); // 文件名称
                    String style = element.attr("style");
                    String[] split = style.split("url\\('");
                    if (split.length != 0) {
                        String[] urls = split[1].split("'\\);");
                        if (urls.length != 0) {
                            String url = urls[0];
                            downloadImg(savePath, name, url, ".png");
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        TaskPoolConfig taskPoolConfig = new TaskPoolConfig();
//        ThreadPoolTaskExecutor executor = taskPoolConfig.myAsyncExecutor();
//        for (int i = 0; i < 246; i++) {
//            int finalI = i;
//            CompletableFuture.runAsync(() -> {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                log.info("任务执行：{}", finalI);
//            }, executor);
//        }

        // 下载图片
        // byFilePath("E:\\em.html", "E:\\baiduImg\\");


        // 测试
        downloadImg("D://", "111", "https://img.zcool.cn/community/0311l9f0hoikhdcycicw5yr3835.png?x-oss-process=image/resize,m_fill,w_520,h_390,limit_1/auto-orient,1/sharpen,100/format,webp/quality,q_100", ".jpg");
//        for (int i = 1; i < 96; i++) {
//            String url = "https://img.zcool.cn/community/0311l9f0hoikhdcycicw5yr3835.png?x-oss-process=image/resize,m_fill,w_520,h_390,limit_1/auto-orient,1/sharpen,100/format,webp/quality,q_100";
//            downloadImg("D://", i + "", url, ".jpg");
//        }



    }
}
